import type { WorkflowChatRequest, WorkflowConversation, WorkflowFile, WorkflowHistoryMessage, WorkflowStreamChunk } from '@/api/chat/workflowTypes';
import { workflowApiService } from '@/api/chat/workflow';
import { useAgentStore } from '@/stores/modules/agent';

// 聊天服务类 - 简洁统一模式
export class ChatService {
  private conversationId: string = '';
  private user: string = '';

  constructor(user?: string) {
    if (user) {
      this.user = user;
    }
  }

  // 会话管理
  setConversationId(id: string) { this.conversationId = id; }
  getConversationId(): string { return this.conversationId; }
  createNewConversation() { this.conversationId = ''; }

  // 用户管理
  getUser(): string {
    // 如果没有设置用户，默认使用guest
    return this.user || 'guest';
  }

  setUser(user: string) { this.user = user; }

  // 获取当前智能体的API密钥
  private getCurrentAgentKey(): string {
    const agentStore = useAgentStore();
    return agentStore.getCurrentAgentKey() || 'app-a02N9D4HWwnY92Bmem4Sdvs0';
  }

  // 数据获取
  async fetchConversations(user: string, lastId: string = '', limit: number = 20): Promise<WorkflowConversation[]> {
    // 使用当前智能体的API密钥
    const apiKey = this.getCurrentAgentKey();
    return await workflowApiService.getConversations({ user, last_id: lastId, limit }, apiKey);
  }

  async fetchMessages(user: string, conversationId: string, lastId: string = '', limit: number = 20): Promise<WorkflowHistoryMessage[]> {
    // 使用当前智能体的API密钥
    const apiKey = this.getCurrentAgentKey();
    return await workflowApiService.getMessages({ user, conversation_id: conversationId, last_id: lastId, limit }, apiKey);
  }

  // 消息发送
  async sendMessage(query: string, inputs: Record<string, any> = {}, files: WorkflowFile[] = [], modelConfig?: { pre_prompt?: string; [key: string]: any }) {
    const requestData: WorkflowChatRequest = {
      inputs,
      query,
      response_mode: 'blocking',
      conversation_id: this.conversationId || undefined,
      user: this.user,
      files: files.length > 0 ? files : undefined,
      model_config: modelConfig,
    };
    // 使用当前智能体的API密钥
    const apiKey = this.getCurrentAgentKey();
    return await workflowApiService.sendMessage(requestData, apiKey);
  }

  async sendMessageStream(
    query: string,
    inputs: Record<string, any> = {},
    files: WorkflowFile[] = [],
    onChunk: (chunk: WorkflowStreamChunk) => void,
    onError?: (error: any) => void,
    agent?: string,
    // modelConfig?: { pre_prompt?: string; [key: string]: any },
  ) {
    // 将agent信息添加到inputs中
    const enhancedInputs = agent ? { ...inputs, agent } : inputs;

    const requestData: WorkflowChatRequest = {
      inputs: enhancedInputs,
      query,
      response_mode: 'streaming',
      conversation_id: this.conversationId || undefined,
      user: this.user,
      files: files.length > 0 ? files : undefined,
      // model_config: modelConfig,
    };

    // 使用当前智能体的API密钥
    const apiKey = this.getCurrentAgentKey();

    await workflowApiService.sendMessageStream(
      requestData,
      (rawChunk: WorkflowStreamChunk) => {
        const parsed = this.parseThinkingAndResult(rawChunk.answer || '');
        onChunk({
          ...rawChunk,
          reasoning: parsed.reasoning,
          result: parsed.result,
          reasoningEnded: parsed.reasoningEnded,
        } as WorkflowStreamChunk);
      },
      onError,
      apiKey,
    );
  }

  // 停止当前任务的生成
  async stopMessage(taskId: string): Promise<boolean> {
    if (!taskId)
      return false;
    try {
      // 使用当前智能体的API密钥
      const apiKey = this.getCurrentAgentKey();
      const resp = await workflowApiService.stopMessage(taskId, this.user, apiKey);
      return resp?.result === 'success';
    }
    catch {
      return false;
    }
  }

  // 文件处理
  processFiles(fileList: any[]): WorkflowFile[] {
    return fileList.map(file => ({
      type: this.getFileType(file.type || file.name),
      transfer_method: 'local_file',
      upload_file_id: file.upload_file_id,
      file_name: file.name,
      file_size: file.size,
    }));
  }

  async uploadFilesIfNeeded(fileList: any[], user: string): Promise<WorkflowFile[]> {
    const result: WorkflowFile[] = [];
    for (const item of fileList || []) {
      if (item.url || item.upload_file_id) {
        result.push(...this.processFiles([item]));
        continue;
      }
      if (item.file instanceof File) {
        // 使用当前智能体的API密钥
        const apiKey = this.getCurrentAgentKey();
        const info = await workflowApiService.uploadFile(item.file, user, apiKey);
        result.push({
          type: this.getFileType(item.file.type || item.file.name),
          transfer_method: 'upload_file',
          upload_file_id: info.id,
          file_name: item.file.name,
          file_size: item.file.size,
        });
      }
      else {
        result.push(...this.processFiles([item]));
      }
    }
    return result;
  }

  // 工具方法
  private getFileType(mimeType: string): 'image' | 'audio' | 'video' | 'document' {
    if (mimeType.startsWith('image/'))
      return 'image';
    if (mimeType.startsWith('audio/'))
      return 'audio';
    if (mimeType.startsWith('video/'))
      return 'video';
    return 'document';
  }

  private parseThinkingAndResult(answer: string): { reasoning: string; result: string; reasoningEnded: boolean } {
    if (!answer)
      return { reasoning: '', result: '', reasoningEnded: false };

    const startIdx = answer.indexOf('<think>');
    const endIdx = answer.indexOf('</think>');

    if (startIdx !== -1 && endIdx !== -1 && endIdx > startIdx) {
      return {
        reasoning: answer.slice(startIdx + 7, endIdx).trim(),
        result: answer.slice(endIdx + 8).trim(),
        reasoningEnded: true,
      };
    }
    if (startIdx !== -1 && (endIdx === -1 || endIdx < startIdx)) {
      return {
        reasoning: answer.slice(startIdx + 7).trim(),
        result: '',
        reasoningEnded: false,
      };
    }
    return { reasoning: '', result: answer, reasoningEnded: true };
  }
}

// 创建默认实例
export const chatService = new ChatService();
